package com.gcd.gym.config;

import com.gcd.gym.utils.JsonResult;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理HandlerMethodValidationException异常
     *
     * @param ex HandlerMethodValidationException异常实例
     * @return 包含错误信息的响应实体
     */
    @ExceptionHandler(HandlerMethodValidationException.class)
    public ResponseEntity<JsonResult<?>> handle(HandlerMethodValidationException ex) {
        String message = ex.getAllErrors().stream()
                .map(MessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return ResponseEntity.badRequest().body(JsonResult.fail(message));
    }
    /**
     * 处理MethodArgumentNotValidException异常
     *
     * @param ex MethodArgumentNotValidException异常实例
     * @return 包含错误信息的响应实体
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<JsonResult<?>> handle(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getAllErrors().stream()
                .map(MessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return ResponseEntity.badRequest().body(JsonResult.fail(message));
    }
}
